package cn.virens.web.components.weixin.config;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;

import cn.hutool.core.convert.Convert;

public class WxMpJCacheCacheConfigStorage extends WxMpAbstractCacheConfigStorage implements InitializingBean {
	public static final String DEFAULT_CACHE_NAME = "weixin-config";

	private javax.cache.Cache<String, String> mChache;
	private javax.cache.CacheManager mCacheManager;

	private String cacheName = DEFAULT_CACHE_NAME;

	public WxMpJCacheCacheConfigStorage(javax.cache.CacheManager mCacheManager) {
		this.mCacheManager = mCacheManager;
	}

	public String getCacheName() {
		return cacheName;
	}

	public void setCacheName(String cacheName) {
		this.cacheName = cacheName;
	}

	@Override
	protected String get(String key) {
		return mChache.get(key);
	}

	@Override
	protected boolean has(String key) {
		// 获取过期时间
		Long expiredTime = Convert.toLong(mChache.get(key + ":expired"), 0L);

		// 如果未过期，判断是否有值
		if (System.currentTimeMillis() < expiredTime) {
			return StringUtils.isEmpty(mChache.get(key));
		} else {
			return true;
		}
	}

	@Override
	protected void put(String key, String value, long timeout) {
		// 计算过期时间
		long expiredTime = System.currentTimeMillis() + timeout * 1000;

		// 将值 & 过期时间分别存入Cache中
		mChache.put(key, value);
		mChache.put(key + ":expired", Long.toString(expiredTime));
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		Assert.notNull(mCacheManager, "Cache Manage is null");

		this.mChache = mCacheManager.getCache(cacheName, String.class, String.class);
	}
}
